package com.it.water.common;

import com.it.water.entity.DataEntity.Image;
import com.it.water.service.ImageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@Component
public class ImageSocketServer {
    @Autowired
    private ImageRepository imageRepository;

    public void startServer() {
        new Thread(() -> {
            try {
                ServerSocket serverSocket = new ServerSocket(8888);
                System.out.println("Socket 服务器已启动，端口：8888");
                while (true) {
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("客户端连接：" + clientSocket.getRemoteSocketAddress());

                    // 保存图片到本地
                    InputStream inputStream = clientSocket.getInputStream();
                    String imageName = UUID.randomUUID().toString() + ".png"; // 生成唯一的图片名称
                    Files.copy(inputStream, Paths.get("C:\\Users\\86139\\Desktop\\图片/" + imageName)); // 替换为你的图片保存路径

                    // 将图片信息保存到数据库
                    saveImageInfoToDatabase(imageName);

                    // 关闭连接
//                    inputStream.close();
//                    clientSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void saveImageInfoToDatabase(String imageName) {
        // 在这里编写将图片信息保存到数据库的逻辑，可以使用JPA、MyBatis等持久化框架
        // 保存图片名称、路径等信息
        Image image = new Image();
        image.setName(imageName);
        image.setImagePath("C:\\Users\\86139\\Desktop\\图片/" + imageName); // 替换为你的图片保存路径
        imageRepository.save(image);
    }
}
